import React, {useEffect, useState} from 'react';
import {Table, Button, Modal, Form, Input, Select, Tag, message} from 'antd';
import {connect} from 'react-redux';
import {get, post} from '../../utils';
import {mUrl} from '../../config';
import Tooltip from "antd/es/tooltip";
import {
    PlusOutlined,
    DeleteOutlined,
    EditOutlined,
    StopOutlined,
    CheckCircleOutlined, 
    ReloadOutlined
} from '@ant-design/icons';
import md5 from 'blueimp-md5';
import utils from "../../utils/utils";
import { defaultPagination } from "./publicComponents";

const Admin = (props) => {
    const [loading, setLoading] = useState(false); // 加载
    const [dataList, setDataList] = useState([]); // 列表
    const [adminVisible, setAdminVisible] = useState(false);
    const [adminData, setAdminData] = useState({});
    const [pagination, setPagination] = useState(Object.assign({}, defaultPagination)); // 页码
    const permissionids = utils.getData('permissionids'); //获取权限id
    const [form] = Form.useForm();
    
    const columns = [
        {
            title: '序号',
            dataIndex: 'id',
            responsive: ['sm'],
            align: 'center',
            width: 100,
            render: (text, record, index) => ((pagination.pageSize * (pagination.current ? pagination.current - 1 : 0)) + index + 1)
        },
        {
            title: '操作',
            responsive: ['lg'],
            align: 'center',
            width: 250,
            render: data => {
                let text;
                let color;
                if (data.userstate === 1) {    //是否启用(1：有效；-1停用；-2删除)
                    text = '停用';
                    color = 'red';
                } else {
                    text = '启用';
                    color = 'rgba(22, 155, 213, 1)';
                }
                return (<div>
                    <Button size='small' style={{color: color, margin: '5px'}}
                            className='btnRight'
                            onClick={() => handleReturn(data)}>
                        {
                            data.userstate === -1 ?  <CheckCircleOutlined/> : <StopOutlined/> 
                        }
                        {text}
                    </Button>
                    <Button size='small' style={{margin: '5px'}}
                            type={'danger'}
                            className='btnRight'
                            onClick={() => handleReturn(data, 2)}><DeleteOutlined/>删除</Button>
                    <Button size='small' style={{margin: '5px'}}
                            type={'primary'}
                            className='btnRight'
                            onClick={() => handleReturn(data, 3)}><EditOutlined/>编辑</Button>
                </div>);
            }

        },
        {
            title: '账号',
            dataIndex: 'loginname',
            width: 150,
            align: 'center',
        },
        {
            title: '角色',
            dataIndex: 'rolename',
            width: 150,
            align: 'center',
        },
        {
            title: '备注',
            dataIndex: 'remark',
            align: 'center',
        },
        {
            title: '状态',
            dataIndex: 'userstate',
            width: 150,
            align: 'center',
            render: isable => {
                let text;
                if (isable === 1) {
                    text = '有效';
                } else {
                    text = '无效';
                }
                return (
                    <Tooltip placement={'topLeft'} title={text}>
                        <Tag color={isable === 1 ? '#0da8de' : '#ff4d4f'}>{text}</Tag>
                    </Tooltip>
                );
            },
        }
    ];
    
    useEffect(() => {
        fetch();
    }, []);

    /**
     * 查询表格数据
     * @param {Object} params 查询条件
     * @param {Object} pagination 分页
     */
    const fetch = async (params={}) => {
        let start = 1;
        if (params.startList > 1) {
                start = params.startList;
        }
        const {state, data} = await get(mUrl.searchUserList, {
            pageNo: start,
            pageSize: pagination.pageSize,
            ...params
        });
        setLoading(false);
        if (state === 1) {
            pagination.total = data.count;
            setPagination(pagination);
            setDataList(data.list);
        }
    };

    // 分页、排序、筛选变化时触发
    const handleTableChange = (page) => {
        pagination.current = page.current;
        pagination.pageSize = page.pageSize;
        setPagination(pagination);
        fetch({
            startList: pagination.current
        });
    };
    
    //启用停用
    const handleReturn = async (value, type) => {
        delete value.loginpwd;
        if (type === 2) {
            if (permissionids) {
                if (permissionids.indexOf('2021010103') !== -1) {
                    Modal.confirm({
                        title: `是否删除管理员${value.name}`,
                        onOk: async () => {
                            value.userstate = -2;
                            const res = await post(mUrl.updateUser, value);
                            if (res.state === 1) {
                                message.info('删除成功');
                                fetch();
                            }
                        },
                    });
                } else {
                    message.warning('对不起您暂时没有删除管理员的权限！');
                }
            }
        } else if (type === 3) {
            if (permissionids) {
                if (permissionids.indexOf('2021010102')!==-1) {
                    setAdminData(value);
                    setTimeout(() => {
                        setAdminVisible(true);
                    }, 500);
                } else {
                    message.warning('对不起您没有编辑管理员的权限');
                }
            }
        } else {
            const text = value.userstate === 1 ? '停用' : '启用';
            Modal.confirm({
                title: `是否${text}管理员${value.name}`,
                onOk: async () => {
                    value.userstate = value.userstate === 1 ? -1 : 1;
                    const res = await post(mUrl.updateUser, value);
                    if (res.state === 1) {
                        message.info(text + '成功');
                        fetch();
                    }
                },
            });
        }
    };
    
    const add = () => {
         if (permissionids) {
             if(permissionids.indexOf('2021010101') !== -1 ) {
                 setAdminVisible(true);
                 setAdminData(false);
             } else {
                 message.warning('对不起您没有新建管理员的权限');
             }
         }
    };
    
    return (
        <div style={{padding: 14, background: '#fff', minHeight: 360}}>
            <label><p>权限管理 / 管理员账号管理</p></label>
            <div style={{marginBottom: 10}}>
                <Button 
                        type={'primary'}
                        className='btnRight'
                        onClick={add}
                >
                    <PlusOutlined/>新建
                </Button>
                <Button
                    onClick={() => fetch()}
                    type={'primary'}
                >
                    <ReloadOutlined />刷新
                </Button>
            </div>
            <Table size="small"
                   dataSource={dataList}
                   rowKey={record => record.id}
                   columns={columns}
                   pagination={pagination}
                   loading={loading}
                   onChange={handleTableChange}
                   bordered
            />
            <br/>
            <AdminModal
                adminData={adminData}
                form={form}
                visible={adminVisible}
                onCancel={() => {
                    form.resetFields();
                    setAdminVisible(false);
                }}
                onSubmit={() => {
                    fetch();
                    setAdminVisible(false);
                }}
            />
        </div>
    );
};

const AdminModal = ({visible, adminData = {}, onSubmit, onCancel, form}) => {
    const [loading, setLoading] = useState(false);
    const [rolename, setRolename] = useState('');
    const [roleList, setRoleList] = useState([]); // 列表

    useEffect(() => {
        if (visible) {
            if (adminData.id) {
                form.setFieldsValue({
                    loginname: adminData.loginname,
                    password: adminData.password,
                    roleid: adminData.roleid,
                    remark: adminData.remark
                });
            }
        } else {
            form.resetFields();
        }
    }, [visible]);

    useEffect(() => {
        roleFindAll();
    }, []);

    const roleFindAll = async () => {
        const res = await get(mUrl.searchAllRole, {});
        if (res.state === 1) {
            setRoleList(res.data);
        }
    };

    const onFinish = (values) => {
        let url = mUrl.addUser;
        if (adminData.id) {
            url = mUrl.updateUser;
            values.id = adminData.id;
        }
        values.rolename = rolename;
        values.name = values.loginname;
        if (values.password) {
            values.loginpwd = md5(values.password);
        }
        setLoading(true);
        post(url, values).then((res) => {
            setLoading(false);
            if (res.state) {
                onSubmit();
            }
        });
    };
    return (
        <Modal
            visible={visible}
            title={adminData.id ? '修改管理员' : '添加管理员'}
            footer={false}
            onCancel={onCancel}
            getContainer={false}
        >
            <div>
                <Form
                    form={form}
                    onFinish={onFinish}
                >
                    <Form.Item name={"loginname"}
                               label={'账号'}
                               rules={[{required: true, message: '请输入账号'}]}
                               style={{marginBottom: 15}}>
                        <Input placeholder={'请输入账号'}/>
                    </Form.Item>
                    <Form.Item name={"password"}
                               label={'密码'}
                               rules={[{required: !adminData.id, message: '请输入密码'}]}
                               style={{marginBottom: 15, marginLeft: adminData.id ? 10 : 0}}>
                        <Input type={'password'} placeholder={'请输入密码'}/>
                    </Form.Item>
                    <Form.Item name={"roleid"}
                               label={'角色'}
                               rules={[{required: true, message: '请选择角色'}]}
                               style={{marginBottom: 15}}>
                        <Select placeholder={'请选择角色'}
                                onChange={(value, option = {}) => {
                                    setRolename(option.children || '');
                                }}>
                            {
                                roleList.map((item) => {
                                    return (
                                        <Select.Option key={item.roleid}
                                                       value={item.roleid}>{item.rolename}</Select.Option>
                                    );
                                })
                            }

                        </Select>
                    </Form.Item>
                    <Form.Item name={"remark"}
                               label={'备注'}
                               style={{marginBottom: 15, marginLeft: 10}}>
                        <Input.TextArea rows={2} placeholder={'请输入备注'}/>
                    </Form.Item>
                    <Form.Item style={{marginTop: 10, textAlign: 'center'}}>
                        <Button
                            loading={loading} htmlType="submit" type={'primary'}
                        >提交</Button>
                        <Button style={{marginLeft: 15}}
                                loading={loading} onClick={onCancel}
                        >取消</Button>
                    </Form.Item>
                </Form>
            </div>
        </Modal>
    );
};

const mapStateToProps = (state) => {
    return {
        ...state.appReducer, // 全局的reducers
    };
};

export default connect(mapStateToProps)(Admin);
